struct ListNode {
  int val;
  ListNode *next;
  ListNode() : val(0), next(nullptr) {}
  ListNode(int x) : val(x), next(nullptr) {}
  ListNode(int x, ListNode *next) : val(x), next(next) {}
};

class Solution {
public:
  ListNode *deleteDuplicates(ListNode *head) {
    ListNode resHead{0, nullptr};
    ListNode *tailPtr = &resHead;
    while (head != nullptr) {
      if (head->next != nullptr && head->val == head->next->val) {
        int dupVal = head->val;
        while (head != nullptr && head->val == dupVal) {
          head = head->next;
        }
      } else {
        tailPtr->next = head;
        tailPtr = tailPtr->next;
        head = head->next;
      }
    }
    tailPtr->next = nullptr;
    return resHead.next;
  }
};
